import React, {Component} from 'react';
import {uniqueId} from 'lodash';
import Header from "./Header";
import Item from "./Item";
import Footer from "./Footer";
import './index.css'

class ToDoList extends Component {

    state = {
        list: [
            {id: uniqueId(), name: '吃饭', done: false},
            {id: uniqueId(), name: '睡觉', done: true},
            {id: uniqueId(), name: '打豆豆', done: false},
        ]
    }

    // 定义处理回车输入的事件
    appendTask = (item) => {
        const fullItem = {
            id: uniqueId(),
            name: item,
            done: false
        }
        this.setState({
            list: [fullItem, ...this.state.list]
        })
    }

    // 修改指定对象的内容
    updateTask = (item) => {
        const newList = this.state.list.map((obj) => {
            if (item.id === obj.id) {
                return {...obj, done: item.done}
            }
            return obj
        })
        this.setState({
            list: newList
        })
    }

    // 删除记录
    deleteTask = (id) => {
        const newList = this.state.list.filter((item) => item.id !== id)
        this.setState({
            list: newList
        })
    }

    // 全选/取消全选
    checkAllTask = (checked) => {
        const newList = this.state.list.map((item) => {
            return {...item, done: checked}
        })
        this.setState({
            list: newList
        })
    }

    // 清除已完成的记录
    cleanFinishAllTask = () => {
        const newList = this.state.list.filter((item) => !item.done)
        this.setState({
            list: newList
        })
    }

    render() {
        return (
            <div className="todo-container">
                <Header onAppendTask={this.appendTask}/>
                <div className="todo-item-warp">
                    {
                        this.state.list.map((item) =>
                            <Item
                                key={item.id}
                                data={item}
                                updateTask={this.updateTask}
                                deleteTask={this.deleteTask}
                            />
                        )
                    }
                </div>
                <Footer
                    data={this.state.list}
                    checkAllTask={this.checkAllTask}
                    cleanFinishAllTask={this.cleanFinishAllTask}
                />
            </div>
        );
    }
}

export default ToDoList;
